import 'package:dio/dio.dart';
import 'package:flutter_easylogger/flutter_logger.dart';

import 'custom_log_interceptor.dart';

class HttpService {
  static final HttpService _instance = HttpService._internal();
  factory HttpService() => _instance;

  late Dio dio;

  final String baseUrl = 'http://192.168.5.12:8080/api';

  HttpService._internal() {
    BaseOptions options = BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 3),
      headers: {
        'Content-Type': 'application/json',
      },
      validateStatus: (status) {
        return status! < 500;
      },
    );

    dio = Dio(options);

    // 自定义日志拦截器
    dio.interceptors.add(CustomLogInterceptor());

    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        // 处理请求
        return handler.next(options);
      },
      onResponse: (response, handler) {
        // 处理响应
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        // 处理错误
        return handler.next(e);
      },
    ));
  }

  Future<Response> post(String path, {dynamic data, Map<String, dynamic>? queryParameters}) async {
    try {
      final response = await dio.post(
          path,
          data: data,
          queryParameters: queryParameters
      );

      // 检查状态码
      if (response.statusCode == 400) {
        throw DioException(
          requestOptions: response.requestOptions,
          response: response,
          message: '请求参数错误: ${response.data}',
        );
      }

      return response;
    } catch (e) {
      Logger.e('捕获到错误: $e');
      rethrow;
    }
  }

  Future<Response> get(String path, {Map<String, dynamic>? queryParameters}) async {
    try {
      final response = await dio.get(path, queryParameters: queryParameters);
      return response;
    } catch (e) {
      Logger.e('捕获到错误: $e');
      rethrow;
    }
  }

  Future<Response> put(String path, {dynamic data, Map<String, dynamic>? queryParameters}) async {
    try {
      final response = await dio.put(
          path,
          data: data,
          queryParameters: queryParameters
      );

      // 检查状态码
      if (response.statusCode == 400) {
        throw DioException(
          requestOptions: response.requestOptions,
          response: response,
          message: '请求参数错误: ${response.data}',
        );
      }

      return response;
    } catch (e) {
      Logger.e('捕获到错误: $e');
      rethrow;
    }
  }

  Future<Response> delete(String path, {Map<String, dynamic>? queryParameters}) async {
    try {
      final response = await dio.delete(path, queryParameters: queryParameters);
      return response;
    } catch (e) {
      Logger.e('捕获到错误: $e');
      rethrow;
    }
  }
}